#!/bin/bash

P6="/dev/mmcblk0p6"
P1="/dev/mmcblk0p1"
APP_PATH="/opt/middleware"
Gold="/home/p1"
ascend_dmi_install_path="/home/data/"
ascend_dmi_run_path="ascend_dmi_tool_path"

CheckP6Mount=`df -h | awk '{if($1=="/dev/mmcblk0p6"){print $6}}'`
CheckP1Mount=`df -h | awk '{if($1=="/dev/mmcblk0p1"){print $6}}'`
GetAtlasEdgePkgName=`ls|grep atlasedge |grep tar.gz$ `
GetHaPkgName=`ls|grep ha |grep tar.gz$ `
GetAscendDmiPkgName=`ls | grep "ascend_dmi_tool" | grep tar.gz$ `

AtlasEdgeTar="AtlasEdge-ARM64-V1.0.0.tar.gz"
AtlasEdgeCms="AtlasEdge-ARM64-V1.0.0.tar.gz.cms"
AtlasEdgeCrl="AtlasEdge-ARM64-V1.0.0.tar.gz.crl"
HAPkgTar="HA-1.3.0.2-aarch64.tar.gz"
HAPkgCms="HA-1.3.0.2-aarch64.tar.gz.cms"
HAPkgCrl="HA-1.3.0.2-aarch64.tar.gz.crl"
HAPkgPath="HA-1.3.0.2-aarch64"
EdgePkg="AtlasEdgePkg"
INSTALL="./install.sh"

RollBack="rollback.sh"
ResetMiddleware="reset_middleware.sh"
date_format="+%Y-%m-%dT%T"

declare -i Err_OK=0 
declare -i Err_MkdirAppPathFailed=1
declare -i Err_SpaceNotEnough=2
declare -i Err_CopyPkgToGoldFailed=3
declare -i Err_CopyRollbackToGoldFailed=4
declare -i Err_UnmountGoldFailed=5 
declare -i Err_InputParamInvalid=6
declare -i Err_MountP9Failed=7
declare -i Err_ExportEnvFailed=8
declare -i Err_MountGoldFailed=9
declare -i Err_MkdirGoldFailed=10
declare -i Err_UpgradeEdgeFailed=15
declare -i Err_UpgradeHAFailed=16
declare -i Err_MkEdgePkgPathFailed=17
declare -i Err_UnzpiEdgePkgFailed=18
declare -i Err_InstallEdgeFailed=19
declare -i Err_MkdirHomeDataFailed=20
declare -i Err_CpCertKeyFailed=21
declare -i Err_CfgEdgeFailed=22
declare -i Err_UnZipHA1Failed=23
declare -i Err_UnZipHA2Failed=24
declare -i Err_InstallHAFailed=25
declare -i Err_UnzipHAFailed=26
declare -i Err_CopyDmiPkgToGoldFailed=27

declare -i Err_HandleKeyManagerError=35
declare -i Err_removeHAError=36
declare -i Err_removeAtlasEdgeError=37
declare -i Err_WaitFDConnectStateFailed=38
declare -i Err_findNoAscendDmiTarPacket=39
declare -i Err_findNoAscendDmiRunPacket=40

LOG_PATH=/var/alog/AtlasEdge_log/
LOG_FILE=middleware.log
UpgradgeLog="$LOG_PATH/$LOG_FILE"
MODE_NAME="middleware.sh"
ATLASEDGE_SPACE_NEED=409600
HA_SPACE_NEED=204800

if [ ! -d ${LOG_PATH} ]; then
  mkdir -p ${LOG_PATH} && chmod -R 700 ${LOG_PATH}
fi
if [ ! -f ${LOG_PATH}/${LOG_FILE} ]; then
  touch ${LOG_PATH}/${LOG_FILE} && chmod 600 ${LOG_PATH}/${LOG_FILE}
fi

_log() 
{
  level=$1
  shift 1
  echo "$(date ${date_format}) -${MODE_NAME}- ${level}- $*" >> ${UpgradgeLog}
  echo "$(date ${date_format}) -${MODE_NAME}- ${level}- $*"
}

logger_Debug() 
{
  echo "$@"
}

logger_Info() 
{
  _log INFO "$@"
}

logger_Warn() 
{
  _log WARN "${color_yellow}$*${color_norm}"
}

logger_Error() 
{
  _log ERROR "${color_red}$*${color_norm}"
}

function check_available_space()
{
  request_space=$1
  software_name=$2
  avail_space=$(df "$APP_PATH" | awk 'NR==2 { print $4 }')
  if [ ${avail_space} -lt ${request_space} ]; then
      logger_Warn "check space fail for ${software_name}, avail=$avail_space request=${request_space}"
      return ${Err_SpaceNotEnough}
  fi
  return $Err_OK
}

function setEnv()
{
  Middleware_Mount=${CheckP6Mount}
  if [ ${Middleware_Mount} ]; then
      APP_PATH=${Middleware_Mount}
  else
      mkdir -p ${APP_PATH}
      if [ $? -ne 0 ];then
          echo "mkdir ${APP_PATH} failed:$Err_MkdirAppPathFailed"  >> ${UpgradgeLog}
      fi  

      mount ${P6} ${APP_PATH}
      if [ $? -ne 0 ];then
          return $Err_MountP9Failed
      fi
  fi

  AtlasEdgeTar=${GetAtlasEdgePkgName}
  AtlasEdgeCms="${AtlasEdgeTar}.cms"
  AtlasEdgeCrl="${AtlasEdgeTar}.crl"
  HAPkgTar=${GetHaPkgName}
  HAPkgCms="${HAPkgTar}.cms"
  HAPkgCrl="${HAPkgTar}.crl"
  HAPkgPath=${HAPkgTar%.tar.gz}

  export PYTHONPATH="${APP_PATH}/AtlasEdge/software/edge_site/opensource"
  if [ $? -ne 0 ];then
    return $Err_ExportEnvFailed
  fi 

  return $Err_OK
}

function setGoldEnv()
{
    P1_Mount=${CheckP1Mount}
    if [ ${P1_Mount} ]; then
        Gold=${P1_Mount}
    else
        mkdir -p ${Gold}
        if [ $? -ne 0 ];then
          return $Err_MkdirGoldFailed
        fi      
        
        blockdev --setrw ${P1}
        mount ${P1} ${Gold}
        if [ $? -ne 0 ];then
          return $Err_MountGoldFailed
        fi
    fi

    for targetfile in `ls $Gold |grep -E "atlasedge|AtlasEdge" |grep tar.gz$ `
    do
      if [ -n "$targetfile" -a -f ${Gold}/$targetfile ]; then
        rm -f ${Gold}/$targetfile
      fi
    done


    for targetfile in `ls $Gold |grep -E "ha|HA" |grep tar.gz$ `
    do
      if [ -n "$targetfile" -a -f ${Gold}/$targetfile ]; then
        rm -f ${Gold}/$targetfile
      fi
    done

    for targetfile in `ls $Gold |grep "ascend_dmi_tool" |grep tar.gz$ `
    do
      if [ -n "$targetfile" -a -f ${Gold}/$targetfile ]; then
        rm -f ${Gold}/$targetfile
      fi
    done

    cp ${GetAscendDmiPkgName} ${Gold}
    if [[ $? -ne 0 ]];then
      umount ${P1}
      return ${Err_CopyDmiPkgToGoldFailed}
    fi

    cp ${AtlasEdgeTar} ${Gold}
    if [ $? -ne 0 ];then
      umount ${P1}
      return $Err_CopyPkgToGoldFailed
    fi

    cp ${HAPkgTar} ${Gold}
    if [ $? -ne 0 ];then
      umount ${P1}
      return $Err_CopyPkgToGoldFailed
    fi

    cp ${ResetMiddleware} ${Gold} 
    if [ $? -ne 0 ];then
      umount ${P1}
      return $Err_CopyRollbackToGoldFailed
    fi

    umount ${P1}
    if [ $? -ne 0 ];then
      return $Err_UnmountGoldFailed
    fi

    return $Err_OK
}

function upgradeAtlasEdge()
{
  mkdir -p $APP_PATH/AtlasEdge/edge_backup

  # set no sys load mode
  bash ${APP_PATH}/AtlasEdge/run.sh config -no_sys_load_mode=1
  bash ${APP_PATH}/AtlasEdge/run.sh config --install_type=Typical --ha_enable=1 --ha_work_path=${APP_PATH}/ha/
  ${APP_PATH}/AtlasEdge/software/edge_site/edge_manager/src/script/upgrade.sh -i force -f ${AtlasEdgeTar} -e delay -s ${AtlasEdgeCms}  -c ${AtlasEdgeCrl}  -t AtlasEdge
  if [ $? -ne 0 ];then
    return $Err_UpgradeEdgeFailed
  fi

  local pre_upgrade_script_path="${APP_PATH}/AtlasEdge/edge_upgrade/software/edge_site/edge_manager/src/script"
  cp -f $pre_upgrade_script_path/edge_main.sh ${APP_PATH}/AtlasEdge/edge_main.sh
  cp -f $pre_upgrade_script_path/edge_upd_effect.sh ${APP_PATH}/AtlasEdge/edge_upd_effect.sh
  return $Err_OK
}

function check_upgrade_scripts_exists() {
    if [[ -f ${APP_PATH}/AtlasEdge/run.sh \
        && -f ${APP_PATH}/AtlasEdge/software/edge_site/edge_manager/src/script/upgrade.sh ]];then
        return 0
    fi
    return 1
}

function install_ascend_dmi_tool(){
    logger_Info "start install ascend-dmi tar path: ${GetAscendDmiPkgName}"
    if [[ ! -f ${GetAscendDmiPkgName} ]]; then
        logger_Info " No find ascend-dmi tar package"
        return ${Err_findNoAscendDmiTarPacket}
    fi

    if [[ -d ${ascend_dmi_run_path} ]];then
        rm -r ${ascend_dmi_run_path}
    fi

    mkdir -p ${ascend_dmi_run_path}
    tar -zxf ${GetAscendDmiPkgName} -C ${ascend_dmi_run_path}
    dmi_tool_file=`find ${ascend_dmi_run_path} -name "Ascend-dmi*.run"`
    if [[ ! -f ${dmi_tool_file} ]]; then
        logger_Info "No find ascend-dmi run package"
        return ${Err_findNoAscendDmiRunPacket}
    fi
    logger_Info "find ascend-dmi run path: ${dmi_tool_file}"
    chmod +x ${dmi_tool_file}
    export USER=$(whoami)
    install_ret=`./${dmi_tool_file} --install --install-path=${ascend_dmi_install_path}`
    logger_Info "install ascend-dmi tool finish: $install_ret"
    rm -rf ${ascend_dmi_run_path}
    return ${Err_OK}
}

function installAtlasEdge()
{ 
  if [ -d ${APP_PATH}/AtlasEdge ];then
     rm -r ${APP_PATH}/AtlasEdge
  fi

  check_available_space ${ATLASEDGE_SPACE_NEED} "AtlasEdge"
  if [ $? -ne 0 ];then
      return $Err_SpaceNotEnough
  fi

  mkdir -p ${EdgePkg}
  if [ $? -ne 0 ];then
    return $Err_MkEdgePkgPathFailed
  fi

  tar xzf ${AtlasEdgeTar} -C ${EdgePkg}
  if [ $? -ne 0 ];then
    return $Err_UnzpiEdgePkgFailed
  fi

  cd ${EdgePkg}
  ${INSTALL} -install_dir ${APP_PATH}
  if [ $? -ne 0 ];then
    return $Err_InstallEdgeFailed
  fi  
  cd ..

  cp -f ${APP_PATH}/AtlasEdge/software/edge_site/edge_manager/config/A500_capability.json ${APP_PATH}/AtlasEdge/software/edge_site/edge_manager/config/default_capability.json
  sed -i 's|"useSecuritySetting".*|"useSecuritySetting":true,|g' ${APP_PATH}/AtlasEdge/software/edge_core/conf/podconfig.json

  if [ ! -d "/home/data/" ];then
    mkdir -p /home/data && chmod 755 /home/data
    if [ $? -ne 0 ];then
      return $Err_MkdirHomeDataFailed
    fi  

    cp -arf ${APP_PATH}/AtlasEdge/software/cert_key/config /home/data/
    if [ $? -ne 0 ];then
      return $Err_CpCertKeyFailed
    fi
  else
    # Atlas 500 场景下已存在密钥材料，需要平滑
    chmod 755 /home/data
    cp -af /home/data/config/main/config/work/.baseMcsCert.enc /home/data/config/main/config/work/.default1.enc
    cp -af /home/data/config/main/config/work/.baseMcsCert.enc /home/data/config/bak/config/work/.default1.enc
    cp -af /home/data/config/main/config/work/.userMcsCert.enc /home/data/config/main/config/work/.default2.enc
    cp -af /home/data/config/main/config/work/.userMcsCert.enc /home/data/config/bak/config/work/.default2.enc
    cp -af /home/data/config/main/config/work/.ipc.enc /home/data/config/main/config/work/.default3.enc
    cp -af /home/data/config/main/config/work/.ipc.enc /home/data/config/bak/config/work/.default3.enc
  fi

  cd ${APP_PATH}/AtlasEdge
  bash ./run.sh config  --install_type=Typical --ha_enable=1 --ha_work_path=${APP_PATH}/ha/
  if [ $? -ne 0 ];then
    return $Err_CfgEdgeFailed
  fi

  # set no sys load mode
  bash ./run.sh config -no_sys_load_mode=1
  if [ $? -ne 0 ];then
    return $Err_CfgEdgeFailed
  fi  
  cd -

  return $Err_OK  
}

function installHA()
{
  if [ -d ${APP_PATH}/ha ];then
     rm -r ${APP_PATH}/ha
  fi

  check_available_space ${HA_SPACE_NEED} "HA"
  if [ $? -ne 0 ];then
      return $Err_SpaceNotEnough
  fi

  mkdir -p ${HAPkgPath}
  tar -xzf ${HAPkgTar} -C ${HAPkgPath}
  if [ $? -ne 0 ];then
    return $Err_UnZipHA2Failed
  fi 

  cd ${HAPkgPath}
  ${INSTALL} -p ${APP_PATH}
  if [ $? -ne 0 ];then
    return $Err_InstallHAFailed
  fi   
  cd ..

  config_ha_log_path
  return $Err_OK
}

function config_ha_log_path() {
    if [ -f ${APP_PATH}/ha/module/hacom/script/config_ha.sh ]; then
        bash ${APP_PATH}/ha/module/hacom/script/config_ha.sh -f /var/alog
        bash ${APP_PATH}/ha/module/hacom/script/config_ha.sh -k /var/alog
    fi
}

function upgradeHA()
{
  ${APP_PATH}/AtlasEdge/software/edge_site/edge_manager/src/script/upgrade.sh -i force -f ${HAPkgTar} -s ${HAPkgCms} -c ${HAPkgCrl} -e delay -t HA
  if [ $? -ne 0 ];then
    return $Err_UpgradeHAFailed
  fi   

  return $Err_OK  
}

function clear_pkgs() {
    [ -n "${HAPkgPath}" ] && rm -rf  "${HAPkgPath}"
    [ -n "${EdgePkg}" ] && rm -rf  "${EdgePkg}"
    rm -rf *atlasedge*.tar.gz*
    rm -rf *ha*.tar.gz*
    logger_Info "clear install file finish"
}

function keyManagerHandle()
{
    rm ${APP_PATH}/AtlasEdge/software/libs/libcrypto.so*

    rm ${APP_PATH}/AtlasEdge/software/libs/libssl.so*

    return $Err_OK  
}

copy_webfile_to_webworkdir(){

  EDGE_WORK_DIR=$1

  if [ ! -d ${EDGE_WORK_DIR}/AtlasEdge/software/edge_portal  ];then
    echo "$(date ${date_format}) web file not exit" >> ${UpgradgeLog}
    return $Err_WebFileNotExist
  fi

  mkdir -p ${EDGE_WORK_DIR}/edge_portal
  cp -rf ${EDGE_WORK_DIR}/AtlasEdge/software/edge_portal/src ${EDGE_WORK_DIR}/edge_portal
  cp -f ${EDGE_WORK_DIR}/AtlasEdge/software/edge_portal/alarm.xml/alarm_info_solution_en.xml /usr/local/nginx/html/manager/i18n/en-US/
  cp -f ${EDGE_WORK_DIR}/AtlasEdge/software/edge_portal/alarm.xml/alarm_info_solution_cn.xml /usr/local/nginx/html/manager/i18n/zh-CN/
  chown -R nobody:nobody ${EDGE_WORK_DIR}/edge_portal
  chown nobody:nobody /usr/local/nginx/html/manager/i18n/en-US/alarm_info_solution_en.xml /usr/local/nginx/html/manager/i18n/zh-CN/alarm_info_solution_cn.xml
  chmod 400 /usr/local/nginx/html/manager/i18n/en-US/alarm_info_solution_en.xml /usr/local/nginx/html/manager/i18n/zh-CN/alarm_info_solution_cn.xml

  if [ -d /usr/local/nginx/html/manager/src/onlinehelp ]; then
    cp -rf ${EDGE_WORK_DIR}/AtlasEdge/software/edge_portal/help/en/*.html /usr/local/nginx/html/manager/src/onlinehelp/en/
    cp -rf ${EDGE_WORK_DIR}/AtlasEdge/software/edge_portal/help/zh/*.html /usr/local/nginx/html/manager/src/onlinehelp/zh/
    chown nobody:nobody /usr/local/nginx/html/manager/src/onlinehelp/en/*.html /usr/local/nginx/html/manager/src/onlinehelp/zh/*.html
    chmod 400 /usr/local/nginx/html/manager/src/onlinehelp/en/*.html /usr/local/nginx/html/manager/src/onlinehelp/zh/*.html
  fi

  return 0
}

function main()
{
  if [ ! $# -eq 1 ];then
    echo "$(date ${date_format}) input param invalid" >> ${UpgradgeLog}
    return $Err_InputParamInvalid 
  fi

  ESPVersion=$1

  setEnv
  ret=$?
  if [ $ret -ne 0 ];then
    echo "$(date ${date_format}) set env failed:$ret" >> ${UpgradgeLog}
    return $ret
  fi
  echo "$(date ${date_format}) set env success:$ret" >> ${UpgradgeLog}

  setGoldEnv
  ret=$?
  if [ $ret -ne 0 ];then
    echo "$(date ${date_format}) set gold env failed:$ret" >> ${UpgradgeLog}
    return $ret
  fi
  echo "$(date ${date_format}) set gold env success:$ret" >> ${UpgradgeLog}

  check_upgrade_scripts_exists
  scripts_cfgs_exists=$?
  if [[ ${scripts_cfgs_exists} -ne 0 && ${ESPVersion} -eq 0 ]];then
    logger_Warn "atlas edge upgrade scripts not exists when esp version is 0"
  fi
  install_ascend_dmi_tool
  if [[ ${ESPVersion} -eq 0 && ${scripts_cfgs_exists} -eq 0 ]];then
      upgradeAtlasEdge
      ret=$?
      if [ $ret -ne 0 ];then
        echo "$(date ${date_format}) upgrade atlasedge failed:$ret" >> ${UpgradgeLog}
        return $ret
      fi
      echo "$(date ${date_format}) upgrade atlasedge success:$ret" >> ${UpgradgeLog}

      upgradeHA
      ret=$?
      if [ $ret -ne 0 ];then
        echo "$(date ${date_format}) upgrade ha failed:$ret" >> ${UpgradgeLog}
        return $ret
      fi  
      echo "$(date ${date_format}) upgrade ha success:$ret" >> ${UpgradgeLog}

  else
      installHA
      ret=$?
      if [ $ret -ne 0 ];then
        echo "$(date ${date_format}) install ha failed:$ret" >> ${UpgradgeLog}
        return $ret
      fi
      echo "$(date ${date_format}) install ha success:$ret" >> ${UpgradgeLog}

      installAtlasEdge
      ret=$?
      if [ $ret -ne 0 ];then
        echo "$(date ${date_format}) install atlasedge failed:$ret" >> ${UpgradgeLog}
        return $ret
      fi
      echo "$(date ${date_format}) install atlasedge success:$ret" >> ${UpgradgeLog}

      copy_webfile_to_webworkdir ${APP_PATH}
      if [ $ret -ne 0 ];then
          echo "$(date ${date_format}) webfile copy failed:$ret" >> ${UpgradgeLog}
          return $ret
      fi
      echo "$(date ${date_format}) webfile copy success:$ret" >> ${UpgradgeLog}

      touch ${APP_PATH}/AtlasEdge/import_esp_config.flag
      logger_Info "create import esp config flag"
  fi

  chown -R HwHiAiUser:HwHiAiUser ${APP_PATH}/AtlasEdge
  chown -R HwHiAiUser:HwHiAiUser ${APP_PATH}/ha
  chmod -R +w ${APP_PATH}/AtlasEdge
  chmod -R +w ${APP_PATH}/ha
  chmod +x ${APP_PATH}/AtlasEdge/software/edge_core/certFD
  chmod -R +x /home/data/config
  keyManagerHandle
  echo "$(date ${date_format}) key manager handle success:$ret" >> ${UpgradgeLog}

  return $Err_OK
}

main "$@"
RESULT=$?
clear_pkgs
exit $RESULT
